﻿using SUNRPA.CONTROLS.IMPL.domain;
using SUNRPA.CONTROLS.IMPL.domain.flowItemParam;
using System.Collections.Concurrent;
using Microsoft.Office.Interop;
using Microsoft.Office.Interop.Excel;
using OfficeExcelApplication = Microsoft.Office.Interop.Excel.Application; 
using SUNRPA.CONTROLS.IMPL.util;
using SUNRPA.CONTROLS.IMPL.interfaces;
using SUNRPA.CONTROLS.IMPL.domain.constant;
using SUNRPA.CONTROLS.IMPL.domain.flowRunningVar;

namespace SUNRPA.CONTROLS.IMPL.controls {
    public class StartExcelNAction:BaseControlActions {
        public override int Execute(int currentIndex, FlowItem item, ConcurrentDictionary<string, ConcurrentDictionary<string, RPAVariableDefineWrapper>> globleData, List<FlowItem> flowItems) {
            StartExcelNParam? param = item.ControlParam as StartExcelNParam;
            int startWay = param.StartWay;
            int driver = param.Driver;
            string excelPath = param.ExcelPath;
            this.GetStringVar(ref excelPath, globleData);

            string outExcelObj = param.OutExcelObj;
            bool isVisable = param.IsVisable;

            string openPassword = param.StartCode;
            this.GetStringVar(ref openPassword, globleData);
            //自动检测查看计算机是否安装offic，若安装使用office，若没有安装查看是否安装wps
            Type? excelType = null;
            if(driver == 0) {
                excelType = ExcelUtil.GetAutoExcelDriver(ref driver);
            } else { 
                if(driver == 1) {
                    excelType = Type.GetTypeFromProgID("EXCEL.Application");
                } else { 
                    excelType = Type.GetTypeFromProgID("ET.Application");//V8版本类型
                    if (excelType == null){
                        excelType = Type.GetTypeFromProgID("Ket.Application");//V9版本类型
                    }
                    if (excelType == null){
                        excelType = Type.GetTypeFromProgID("Kwps.Application");//V10版本类型
                    }
                }
            }
            if(excelType == null) { 
                throw new RpaRuntimeException("未安装excel");
            }
            ExcelUtil excelUtil = new ExcelUtil(excelType);
            Workbook wb;
            if(startWay == 0) {
                //密码暂时不考虑
                wb = excelUtil.Open(isVisable, excelPath, openPassword);
            } else { 
                wb = excelUtil.Create(isVisable, excelPath);
            }
            if(wb == null) { 
                throw new RpaRuntimeException("启动excel错误");
            }
            this.saveVar(globleData, outExcelObj, new ExcelModel(outExcelObj, wb), DefaultContents.RUNNING_PARAM);
            return currentIndex;
        }
    }
}
